<template>
  <div ref="editorContainer" class="monaco-editor-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from "vue";
import * as monaco from "monaco-editor";

const props = defineProps<{
  modelValue: string;
  language?: string;
  height?: number;
  theme?: string;
}>();

const emit = defineEmits<{
  (e: "update:modelValue", value: string): void;
  (e: "change", value: string): void;
}>();

const editorContainer = ref<HTMLElement>();
let editor: monaco.editor.IStandaloneCodeEditor;

onMounted(() => {
  if (!editorContainer.value) return;

  editor = monaco.editor.create(editorContainer.value, {
    value: props.modelValue,
    language: props.language || "javascript",
    theme: props.theme || "vs-light",
    minimap: { enabled: false },
    scrollBeyondLastLine: false,
    lineNumbers: "on",
    automaticLayout: true,
    tabSize: 2,
    fontSize: 14,
  });

  editor.getModel()?.updateOptions({ tabSize: 2 });

  editor.onDidChangeModelContent(() => {
    const value = editor.getValue();
    emit("update:modelValue", value);
    emit("change", value);
  });

  if (props.height) {
    editorContainer.value.style.height = `${props.height}px`;
    editor.layout();
  }
});

onBeforeUnmount(() => {
  if (editor) {
    editor.dispose();
  }
});

watch(
  () => props.modelValue,
  (value) => {
    if (editor && value !== editor.getValue()) {
      editor.setValue(value);
    }
  }
);
</script>

<style scoped>
.monaco-editor-container {
  width: 100%;
  height: 300px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
</style> 